package com.feibi.study.Basic

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.Nullable
import androidx.fragment.app.Fragment
import com.feibi.study.Dialog.CustomDialog
import com.feibi.study.R

abstract class BasicFragment : Fragment() {
    var isLoading = false

    @Nullable
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(getResId(), null, false)
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        initLoadingDialog()
        super.onViewCreated(view, savedInstanceState)
    }

    abstract fun getResId(): Int

    var loadingDialog: CustomDialog? = null
    private lateinit var tv_loading: TextView

    protected fun initLoadingDialog() {
        val view: View = LayoutInflater.from(context).inflate(R.layout.dialog_loading, null)
        tv_loading = view.findViewById(R.id.tv_loading)
        loadingDialog = context?.let { CustomDialog(it, view) }!!
        loadingDialog?.setCancelable(false)
    }

    open fun showLoading() {
        showLoading("")
    }

    open fun showLoading(text: String) {
        tv_loading.text = text
        tv_loading.visibility = if (text.isBlank()) View.GONE else View.VISIBLE
        loadingDialog?.show()
    }

    fun dismissLoading() {
        loadingDialog?.dismiss()
    }


    /**
     * 显示toast
     *
     * @param msg      内容
     * @param duration 时间
     */
    fun showToast(msg: String?, duration: Int = Toast.LENGTH_SHORT) {
        context.let { Toast.makeText(it, msg, duration).show() }
    }

    /**
     * 获取状态栏高度
     */
    open fun getStatusBarHeight(): Int {
        var statusBarHeight1 = -1
        val resourceId =
            resources.getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0) {
            statusBarHeight1 = resources.getDimensionPixelSize(resourceId)
        }
        return statusBarHeight1
    }

}

